<?php
session_start();

include 'includes/cDatabase.php';
include 'includes/cPage.php';
include 'includes/cDates.php';

if (isset($_GET["Posn"]))
{
	$_SESSION['position'] = @$_GET['Posn'];
}
else if (isset($_GET["Formation"]))
{	
	if ($_GET["Formation"] == 'randomteam')
	{
		$_SESSION['formation'] = randomTeam();
	}
	else if ($_SESSION['formation'] != $_GET["Formation"])
	{
		// the formation has changed.
		// 0  1234 5678 910
		if ($_SESSION['formation'] == 442)
		{
			switch ($_GET["Formation"])
			{
				default:
				case 433: $_SESSION['playerArray'][8] = NULL; break; // Delete the last midfielder
				case 451: $_SESSION['playerArray'][9] = NULL; break; // Delete the first striker
				case 343: $_SESSION['playerArray'][4] = NULL; $_SESSION['playerArray'][8] = NULL; break; 
				case 352: $_SESSION['playerArray'][4] = NULL; break; 
				case 532: $_SESSION['playerArray'][5] = NULL; break;
			}
		}
		else if ($_SESSION['formation'] == 433)
		{
			switch ($_GET["Formation"])
			{
				default:
				case 442: $_SESSION['playerArray'][8] = NULL; break;
				case 451: $_SESSION['playerArray'][8]; $_SESSION['playerArray'][9] = NULL; break;
				case 343: $_SESSION['playerArray'][4] = NULL; break; 
				case 352: $_SESSION['playerArray'][4] = NULL; $_SESSION['playerArray'][8]; break;
				case 532: $_SESSION['playerArray'][5] = NULL; $_SESSION['playerArray'][8] = NULL; break;
			}
		}
		else if ($_SESSION['formation'] == 451)
		{
			switch ($_GET["Formation"])
			{
				default:
				case 442: $_SESSION['playerArray'][8] = NULL; break;
				case 433: $_SESSION['playerArray'][8]; $_SESSION['playerArray'][9] = NULL; break;
				case 343: $_SESSION['playerArray'][4] = NULL; $_SESSION['playerArray'][8] = NULL; $_SESSION['playerArray'][9] = NULL; break; 
				case 352: $_SESSION['playerArray'][4] = NULL; $_SESSION['playerArray'][9]; break;
				case 532: $_SESSION['playerArray'][5] = NULL; $_SESSION['playerArray'][9] = NULL; break;
			}
		}
		else if ($_SESSION['formation'] == 343)
		{
			switch ($_GET["Formation"])
			{
				default:
				case 442: $_SESSION['playerArray'][4] = NULL; $_SESSION['playerArray'][8] = NULL; break;
				case 433: $_SESSION['playerArray'][4]; break;
				case 451: $_SESSION['playerArray'][4] = NULL; $_SESSION['playerArray'][8] = NULL; $_SESSION['playerArray'][9] = NULL; break; 
				case 352: $_SESSION['playerArray'][8] = NULL;
				case 532: $_SESSION['playerArray'][4] = NULL; $_SESSION['playerArray'][5] = NULL; $_SESSION['playerArray'][8] = NULL; break;
			}
		}
		else if ($_SESSION['formation'] == 352)
		{
			switch ($_GET["Formation"])
			{
				default:
				case 442: $_SESSION['playerArray'][4] = NULL; break;
				case 433: $_SESSION['playerArray'][4]; $_SESSION['playerArray'][8]; break;
				case 451: $_SESSION['playerArray'][4] = NULL; $_SESSION['playerArray'][8] = NULL; break; 
				case 343: $_SESSION['playerArray'][8] = NULL;
				case 532: $_SESSION['playerArray'][4] = NULL; $_SESSION['playerArray'][5] = NULL; break;
			}
		}
		else	// 532
		{
			switch ($_GET["Formation"])
			{
				default:
				case 442: $_SESSION['playerArray'][4] = NULL; break;
				case 433: $_SESSION['playerArray'][4]; $_SESSION['playerArray'][8]; break;
				case 451: $_SESSION['playerArray'][4] = NULL; $_SESSION['playerArray'][8] = NULL; break; 
				case 352: $_SESSION['playerArray'][4] = NULL; $_SESSION['playerArray'][8] = NULL; break; 
				case 343: $_SESSION['playerArray'][8] = NULL; 
			}
		}
	}
	$_SESSION['formation'] = $_GET["Formation"];
}
else if (isset($_GET["PlayerCodeOut"]))
{
	// Find this player in the array and blank him out
	for ($i = 0; $i < 11; $i++)
	{
		if ($_SESSION['playerArray'][$i] == $_GET["PlayerCodeOut"])
		{
			$_SESSION['playerArray'][$i] = NULL;
			//echo "<BR>OUT:".$_GET["PlayerCodeOut"];
		}
	}
}
else if (isset($_GET["PlayerCodeIn"]))
{
	if (isset($_SESSION['playerArray']))
	{
		// loop through the session array with foreach
		$found = 0;
		if ($_GET["PlayerCodeIn"]<2000)
		{
			// Goalkeeper
			$min = 0; $max = 0;
		}
		else if ($_GET["PlayerCodeIn"]<3000)
		{
			switch ($_SESSION['formation'])
			{
				default:
				case 433:
				case 451:
				case 442: $min = 1; $max = 4; break;
				case 343:
				case 352: $min = 1; $max = 3; break;
				case 532: $min = 1; $max = 5; break;
			}
		}
		else if ($_GET["PlayerCodeIn"]<4000)
		{
			// Midfielder
			switch ($_SESSION['formation'])
			{
				default:
				case 433: $min = 5; $max = 7; break;
				case 451: $min = 5; $max = 9; break;
				case 442: $min = 5; $max = 8; break;
				case 343: $min = 4; $max = 7; break;
				case 352: $min = 4; $max = 8; break;
				case 532: $min = 6; $max = 8; break;
			}
		}
		else
		{
			// Striker
			switch ($_SESSION['formation'])
			{
				default:
				case 433: $min = 8; $max = 10; break;
				case 451: $min = 10; $max = 10; break;
				case 442: $min = 9; $max = 10; break;
				case 343: $min = 8; $max = 10; break;
				case 352: $min = 9; $max = 10; break;
				case 532: $min = 9; $max = 10; break;
			}
		}
		
		for ($i = $min; $i <= $max; $i++)
		{
			if ($_SESSION['playerArray'][$i] == NULL)
			{
				$_SESSION['playerArray'][$i] = $_GET["PlayerCodeIn"];
				$found = 1;
				break;
			}
			//echo "<BR>".$i." ".$_SESSION['playerArray'][$i];
		}
		if ($found == 0)
		{
			$_SESSION['playerArray'][$min] = $_GET["PlayerCodeIn"];
		}
	}
	else
	{
		$_SESSION['playerArray'][0] = $_GET["PlayerCodeIn"];
	}
}
else
{
	$Position = 'GK';
}

$cPage = new page("Team Builder");
echo $cPage->getTitle();
echo $cPage->pageStringStart();
echo $cPage->contentStringStart();
?>

<SCRIPT>
<!--
var enemy_name_1 = new Array(
"Subutteo Skills","Your Name Here","Team","Grasshopper","Southampton","Portsmouth",
"Manchester","Liver","BistoFace","Everton","Fem","Fembot",
"Belligerent","Carrot","Champion","Jeriatrick","Fantasy","Dream Team",
"The Welsh","Ericsson","DMV","England","Scotland","Face Man",
"Rovers","The Best Eleven","Benny The","Carlos The","Conrad","Quincey","Willy Del","Moneybags","Brave Arse",
"Braveheart","Sir Bravary Of","Sir Kit","Sir Barnardos","Sir Idiot Club","Sir Mingot Team",
"Jesus","Church","Church Of","The PID","Tim","Fairy",
"Wanton","Gillian","Stepmotor","Fingermouse","Gay Boys ","Goblins One Bod",
"Catscan","Nob","Jockey","Merchant","Merchant Of","Cowskin",
"Shrimper","Bovine Troop","Hairstyle","Drag Queen","Maximum Drag Queen","Tie Fighter",
"Thai Boy","Prawn","Headacher Of","Dreadnought","Twin Bitch","Scoops",
"Fat Man","Fat Boy","Fat Girl","Rabbit Head","Bunny","Bunty",
"Butlins","Eagle Breath","Eagle Eyes","Action Boy","Amanda Panda","Four Eyes",
"Stinger","Wimbledon","The Queen Of","Hotdog The","Rawdog","Reds",
"The King Of","Prince","James","Blues","India","Kentucky",
"Superintendent","Doctor","Solicitor Of","Tandbergian","PSU","Lizard",
"Labia Of","Equine","Feline","Evil Cat Of","Robot Of","Big Lips",
"Teddy Boy","Teddy","I Robot","Big Ears","The Guards Of","Legwarmer",
"Evil Bitch","Clango","Mungo","Mungo Jerry","Zippy","Lovely Lad",
"Club","Snoop","Dog","Snoop Doggy","Hatglasses Von","Ludwig's",
"Parliament","The Parliament Of","Magician","Arnold","Cliff","Serial",
"Watchcloth","Sinker","Battle Axe","Swordsman","Lance's","Billy No Mates The",
"Mateyboy","Tiger Balm","Ramos Team","Darth","FC","Skanky Pants",
"The Y-Fronts Of","Hensman's","Lump Twang","Flipper","Hugh's","Collier's",
"Lobster Van","Nappy Man","Shindler","Nurdle","Jimmy Clap The","Four Eyes",
"Evil Henchmen Of","Rudy","Log File","Hotdog The","Daddy","Mummy",
"The Mummy Of","Uncle","Auntie Bitch The","Grandmother Of","Sister","Brother",
"Monkey Boy","Fish Lips","Gill Squad","Romper","Squasher","BA",
"BEng Hons","Murdoch","Club","Klub","The Robots Of","Big Lips",
"Teddy Boy","Teddy","I Robot","Big Ears","Boomer's","The Hater Of",
"AFC","Loverboy","The Great Lover","The Unexpected","Sweaty","Bruiser The",
"The Saxon","The Roman","Middle Crap","Toilet Of","Sidney's","Sidney Kidney",
"St Bernard","Saint Augustine Of","Joseph","Joseph Of","Judas","Quintus",
"Barry Von","Nicholas Of","Twit","Twat Face","Roger Red Hat","Harem",
"Charion","Beta Boy","Alpha The","Lapdog","Troop Cloop The","Johno",
"The Great Fighter","The","Baps","Titty Boobs","Navy Boy","Centurion Of",
"The Great","The Evil Twin Of","The Fish Kid Of","Little Boy","Tentacle","The Nucleus Of",
"Andromeda Of","Kevin","Crax","Claxxon Death Of","The Tempest Of","Mr Lister",
"Hitler","Little Fairy","Crax","The Cowboy","The Cowgirl","HMS",
"Dead Ringer For","Blagger","Cardboard","The Corrugated","The Wagoner Of","Andrey The",
"Plug","Beard Mode","Beardsley Of","Ugly Kid","The Machine Of","Girly",
"Pretty Boy","Parrot Man","Shin Pad","Grasshopper Del","The Mexican","The Royal",
"The British","The Welsh","The Evil","Big head","Big Foot And The","The Provincial",
"Clawfinger","Funklove","Modem","Japanese","Flip Mobile","Bulbous",
"Chav Boy","Squirrel","Lovely Club","Bag Lady","Latex Fist","Latex Men Of",
"Jeepers","Buster","Jehovah","Warlord","Scavanger Of","The Nutty Tooth",
"Dolphin","Munter","Bigamist","Hooty","Trickster Of","The School Of",
"Blubber Boy","Soap Dodger","Shirty Man","Panda Breath","Cupped","Cupid",
"Single Man","The Married","The Coveted","The Religious","The Infamous","The Toothless",
"Cycloptic","Trouser Snake Of","Pharoah","Canine","The Vulpine","Real",
"Little Miss","Real Bad","Men Of","The Lady Of The","The Human","The Fearless",
"The Fathers Of","The Ancient Fathers Of","Mother Of","The Great","The Secret","The Famous",
"The Fantastic","The Incredible","The Bride Of","The Two Sons Of","The Ark Of","Colonel",
"The Paradoxical","The Diabolical","The Fair","The Silly","The Big Old","The Seven Year",
"The Little","The Fire Of","The Feared","The Stupid","The Dumb","The Thick",
"The City Of","Kangaroo Jack The","Jack Of","Puck Of","Shakespear","Churchill The",
"Henry The","DJ","The Angry","The Technician Of","CEO","Twenty Five",
"Servent Of","Thor","Trumpet Bones","Fat Ass The","The Fat American","The Arrogant",
"The Knights Of","Sinbad","Pauper","Scottish McSlut The","The Pixie From","The Dead Elf Of",
"The Teenager Of","Spotty","The Spotty Youth Of","Old Lady","HRH","Macky Jack The",
"Hoots McDrunk The","Drunk Scotsman Of","The Great Unwashed","Turncoat","The Turncoat Of","Greenhorn Of",
"Vag The Badge","Fat Blonde Del","El Slut","The Congratulated","Return Of","Benign",
"The Fifteenth","The Seven","The Five","The Flogger","The Paper","The Metal",
"The Wooden","The Trooper Of","The Five Eyes Of","The Lovely Slut","The Anti Basket From","The Man From",
"Leather Boobs Del","Rat Boy","Whistle Blower","The Prince Grabber Of","The Rammer Of","Backdoor Boy",
"Hugh Baird", "Mark Collier", "Raol Moat", "Maxine", "Sausmologer", "Gareth Batten",
"Zagreb", "The Bearded Wonderful", "Football", "Soccer", "Football's", "The Chaps", "The Boys of",
"Peckham's","Collier","Daniel Wilderbeast's","Man of Hen","The Crusty","Odd Bod's","The Mini",
"Meon Valley","Ramos","Richard White's","The Directors of","Ericsson Big Wig","The Turdy","Poo Poo Von",
"The Dribbly","The Bearded","The 1960s","The Milk Cup","The Trophyless","Top Of The League","Bottom Of The",
"G Diddy's","Tic Tac Tit","The Wallies From","The Men From","My Mum's","The Great","The Cherished"
)

var enemy_name_2 = new Array(
"Didlickers","Scrotal Votes","Ball Bags","Balls","Kickers","Handy Boys","Supporters Club",
"League Toppers","Bottom Toppers","Bum Hole Coverers","A Holes","Flap Sealers","Marvels","Bambinos",
"Shirt Pull Utd","Ununited","Oyster Catchers","Old Men","Clingy Girlfriends","Under The Thumbs","Nagging Wives",
"Shoe Buckelers","Teaport Trilogy","Trilogy","Bandits","Big Willy XI","Dicky Boys","Over Pant XI",
"Gosport","Hedge End XI","Scummers","Skates","Devils","Before Skin XI","Blonde Girls",
"United","City","Rovers","Town","XI","Eleven",
"Argyle","Village","Team Boys","Losers","Idiots","Crowd Pleasers",
"Layabouts","Ericsson Club","Club","Clout Club","Mongeese","Catholic Boys",
"Squad","Death Squad","Clowns","VANC Invaders","Space Clowns","Aggressors",
"Jesus Death Squad","Man Lovers","Haters","Man Boobs","Crosby","Eraserheads",
"Rovers United","Rebellion-Smith Squad","Ericssonians","Ex Handbagers","Tand Burglers","And Sons",
"McDanger Club","Mould Daggers","Daggers","Rag Week Clubbers","Bunter Boys","Menacers",
"Minxes","Bash Lovely Boys","Wash Cloths","Bitch Cloths","Bitchers","Flank Deathgrips",
"Decibel Ricketts","Flamingo Touchers","Boomerang Death Grips","Superbitches","Friends","Foes",
"Fiend Gloves","Carplovers","Fire Rocket Squad","Glove Boys","Wagon Bitches","Tele Bitches",
"Nervous Head Grafts","Von Boobytraps","Simpleton Team Mug Dogs","Simpleton Lovers","Simpleton Boomerangs","Gift Horses",
"Mouthwaterers","Congo Squad Of Doom","Kong-Bapsteins","McDonald Cheese Boys","Burger Lovers","String Wanderers",
"Puppet Breathers","Rye Catchers","Worm Canners","Hitchins Team One","Catty Wombs","Womb Simpsons",
"BobbleHats","Hate Mongers","Von Cogs FC","Von Clogs Utd","Clogs-Murphy FC","Wheely Bitch FC",
"Malevolence FC","FC","Penzance","Hampshire FC","O'Minge FC","Reserves",
"Cat XI","Zippy Bungler XI","Mandleson XI","Moutray XI","Baker XI","Injury Death Squad",
"Beefcakes","Urinal Death Wish XI","Toilet Heads","Cricket XI","Truslove Von Goose XI","Footballers",
"Guy Lords","Fur Pack Lurpack XI","Fictional Death Heads","Madrid","Puppy Lovers","Dog Breath FC",
"Enter Key FC","Shift Escape FC","Bros","Dooby Brothers","Brothers","Venison XI",
"Williams Del Monte XI","Augustus","Caesars Dick Utd","Dicky Bird Lovers","Naval Back Scratch XI","Suckers",
"Aero Cogs","Bendy Lips Rovers","Chapstick-Bentley XI","Hand Grip XI","Stronghold","Syndrome Team Five",
"Gangreen City","Babylon City","Envelopers","Destroyers","Cargo Health Squad","Enema XI",
"Ballistics","Internal Movements","Bacterial Team","Viral XI","Window Cleaners","Milkmen",
"Mini Men","Mini Mentals","Skid Baths","Goosers","Skywalkers","Death Team",
"Dab Hands","Cleaners","Punishers","Duck Washers","McNothings","PROM Blowers",
"Rotate Boobery XI","Rippers","Hoovers","Traitors","Unix Administrators","Iscariots",
"Tronguys","Tronsvestites","Train Spotters","Embarkers","Hijackers","Hijacker Mouthpiece XI",
"Mouth Watchers","Clips Snippers","Rodents","Rogue Of Doom","Venice","Bummy Boys",
"White Space","Origami","Bloomingdale","Mummy Boys","Baird Boys","Craps Lockers",
"Story Tellers","All Trades","Compass Tent Love Utd","Frustraters","Woman Toucher XI","Horse Squad",
"English Gentlemen","Yank XI","Crank Squad","Bankers","Chronicle Of Doom Squad","Phase Diagrams",
"Smith Charts","Warblers","Jerusalem","Salem","Of Nazareth","Kelsey",
"Charing Cross","Evans-Backlash XI","Lush XI","Lushmeister Team","Dogsford","Port",
"Mashers","Jacket Requirement XI","Sanguine XI","Beaver Retrievers","Beaver Recipients","Shirty Lovers",
"Skirt Lifters","Fat Boys","Hash Keys","Jumper Leads","Scanned Dicks","Moby Dicks",
"Shirt Lifters","Prison Love XI","Melrose Place","Sydney Opera House","House Of Lies","Tudor",
"Regal Bitches","Creepy Men","Brain Tamperers","Arm Grabbers","Back Breakers","Keeper Touchers",
"Saturn","Mars","Apocalypse","Foreskinny Lads","Bland Ladies","Dead Goalkeepers",
"Planet Earth","80s Pop Love","German Grandmothers","Rooneys","Whooping Coughs","Saints",
"Cads","Bounders","Seemingly Nothing","Blank Faces","Cuboid Lovers","Fat Americans",
"Organised Activities","Silent Fun","Muted Lovers","Blank Facers","Spenders","Plain English Girls",
"Iron Death Squad","Wheeling Steelers","Dead Birds","Prehistoric Shifters","Tectonic Fun Boys","Spanish Pushovers",
"Thong Lovers","Castle Death Boys","Painful Things","Illegal Activities","General Evil Folk","Dead Poets",
"Europe","Antarctica","Frozen Fun Rovers","Freezers","Lippy Bitches","Dressing Gowns",
"Neptune","Pluto","Southern Hemisphere","Balti","Creamy Substance Team Ten","Dinner Jackets",
"Potters","Strangelovers","Boys","Puzzle Beasts","Folk","Vagifem Men XI",
"Map Eaters","Censored XI","Bear Huggers","Animal Lovers","Creepers","Dutch Baps",
"Benders","Gaybees","Young Boys","Crop Dusters","Zurich","Mincer Pincers",
"Zealots","Magdalane XI","Racists","Sexist Toads","Vinegar Strokers","Local Boys",
"Bum Grabbers","Knee Thievies","Robber Bandits","Anti-Girl Cream XI","Rubber Dolls","Dolly Men",
"Sweety Lips","Lip Service XI","Crows Feet XI","Melchester","Adultery XI","Local Mincers",
"Gent Stoppers","Spy Catchers","Bounty Hunters","Munter Hunters","Hunters","Deliverence XI",
"Whopper Boob Bag XI","Space Hoppers","Trained Boys","Slappers","Breakfast Club Boys","Lunch Infesters",
"City Bankers","Spurious Team","Investment Bankers","Face Receivers","Fat Lovers","Lipid Investigators",
"Cod Bods","Raol Moatdrid","Christ","Anti Christ","Crucifix","Wombs",
"Odd Bods", "Portsmouth FC", "Carlisle", "Maximum Irritation", "Ramos Raiders", "Rabdog Goblins"
)
var message="Please Reboot Your Face";
function click(e) 
{
	if (document.all) 
	{
		if (event.button == 2) 
		{
			alert(message);
			return false;
		}
	}
	if (document.layers) 
	{
		if (e.which == 3) 
		{
			alert(message);
			return false;
		}
	}
}
if (document.layers) 
{
	document.captureEvents(Event.MOUSEDOWN);
}
document.onmousedown=click;

function generateTeam()
{
	var number_one;
	var number_two;
	number_one = get_random(enemy_name_1.length);
	number_two = get_random(enemy_name_2.length);
	generate_enemy(number_one, number_two);
}
function get_random(num_choices)
{
    var ranNum= Math.round(Math.random()*num_choices);
    return ranNum;
}
function generate_enemy(number_one,number_two)
{
	enemy_name = enemy_name_1[number_one] + " " + enemy_name_2[number_two];
	document.write(enemy_name);
	return enemy_name;
}
// -->
</script>

<?php
define("MAXVALUE", "50");

$cDatabase = new database();

$connect = $cDatabase->connectToDatabase();
$activeDatabase = $cDatabase->getActiveDatabase($connect);
	
$db = $cDatabase->selectDatabase($connect, $activeDatabase);


class player {
	var $memberPlayerCode;
	var $memberPlayerPosition;
	var $memberPlayerValue;
	var $memberPlayerName;
	var $memberPlayerTeam;

	function player() 
	{
	}
	function addPlayer($code, $host, $user, $password, $activeDatabase)
	{
		if ( (($length = strlen($code)) != 3) && (($length = strlen($code)) != 4) )
		{
			//echo"<BR>Error detected for Player Code ".$code.": expected length 3 received length ".$length;
			$error = 1;
			return $error;
		}
		$this->memberPlayerCode = $code;
		$cDatabase = new database();

		$connect = $cDatabase->connectToDatabase();
		$activeDatabase = $cDatabase->getActiveDatabase($connect);
	
		$db = $cDatabase->selectDatabase($connect, $activeDatabase);

		$query = "SELECT playerCode, playerPosition, playerValue, playerTeam, playerName FROM playerlist WHERE playerCode='".$this->memberPlayerCode."'";
		
		$result = mysqli_query($connect, $query);
		$row = mysqli_fetch_array($result, MYSQLI_ASSOC);
		
		if ($row["playerPosition"] == NULL)
		{
			echo"<BR>Player ".$this->memberPlayerCode." has invalid position in playerlist database.";
			$error = 1;
		}
		$this->memberPlayerPosition = $row["playerPosition"];
		
		if ($row["playerValue"] == NULL)
		{
			echo"<BR>Player ".$this->memberPlayerCode." has invalid value playerlist database.";
			$error = 1;
		}
		$this->memberPlayerValue = $row["playerValue"];
		$this->memberPlayerName = $row["playerName"];
		$this->memberPlayerTeam = $row["playerTeam"];
		//echo "player ".$this->memberPlayerCode." position ".$this->memberPlayerPosition;
		//echo "player ".$this->memberPlayerCode." value ".$this->memberPlayerValue;
		
		mysqli_close($connect);
		return 0;
	}
	function getPosition()
	{
		return $this->memberPlayerPosition;
	}
	function getCode()
	{
		return $this->memberPlayerCode;
	}
	function getValue()
	{
		return $this->memberPlayerValue;
	}
	function getName()
	{
		return $this->memberPlayerName;
	}
	function getTeam()
	{
		return $this->memberPlayerTeam;
	}
}
	

{
	$error = 0;
	$numGK = 0;
	$numDEF = 0;
	$numMID = 0;
	$numATT = 0;
	$totalValue = 0;
	
	for ($i = 1; $i <= 11; $i++)
	{
		$memberPlayer[$i] = new player;
		if ($i < 10)
			$variable = "playerCode0".$i;
		else
			$variable = "playerCode".$i;
		$error |= $memberPlayer[$i]->addPlayer($_SESSION['playerArray'][$i-1], $host, $user, $password, $activeDatabase);
	}
	
	// Do checks
	for ($i = 1; $i <= 11; $i++)
	{
		switch($memberPlayer[$i]->getPosition())
		{
			case "GK": 	$numGK++;
						break;
			case "DEF":	$numDEF++;
						break;
			case "MID": $numMID++;
						break;
			case "ATT":	$numATT++;
						break;
			default:	//echo"<BR>Error detected for player code ".$memberPlayer[$i]->getCode().". Position not recognised.";
						$error = 1;
						break;
		}
		$totalValue += $memberPlayer[$i]->getValue();
	}
	if (bcsub(MAXVALUE, $totalValue, 1) < 0)	// To avoid floating point inaccuracies
	{
		$error = 1;
		echo"<BR>Team value ".$totalValue." exceeds maximum value ".MAXVALUE;
	}

	// Check the 4 possible formations
	// Check for 3-5-2
	$pass = 0;
	if (($numGK == 1) && ($numDEF == 3) && ($numMID == 5) && ($numATT == 2))
	{
		$pass |= 1;
	}
	// Check for 4-4-2
	if (($numGK == 1) && ($numDEF == 4) && ($numMID == 4) && ($numATT == 2))
	{
		$pass |= 1;
	}
	// Check for 4-3-3
	if (($numGK == 1) && ($numDEF == 4) && ($numMID == 3) && ($numATT == 3))
	{
		$pass |= 1;
	}
	// Check for 4-5-1
	if (($numGK == 1) && ($numDEF == 4) && ($numMID == 5) && ($numATT == 1))
	{
		$pass |= 1;
	}
	// check for 3-4-3
	if (($numGK == 1) && ($numDEF == 3) && ($numMID == 4) && ($numATT == 3))
	{
		$pass |= 1;
	}
	// check for 5-3-2
	if (($numGK == 1) && ($numDEF == 5) && ($numMID == 3) && ($numATT == 2))
	{
		$pass |= 1;
	}
	
	echo "<table><tr><td>";
	
	echo "<table><tr><td>";
		
	echo "<td><FORM ACTION=\"$PHP_SELF?Formation=442\" METHOD=\"POST\">";
	echo "<input name='code' type='submit' id='formation' value='4-4-2'>";
	echo "</form></td>";
	
	echo "<td><FORM ACTION=\"$PHP_SELF?Formation=451\" METHOD=\"POST\">";
	echo "<input name='code' type='submit' id='formation' value='4-5-1'>";
	echo "</form></td>";
	
	echo "<td><FORM ACTION=\"$PHP_SELF?Formation=352\" METHOD=\"POST\">";
	echo "<input name='code' type='submit' id='formation' value='3-5-2'>";
	echo "</form></td>";
	
	echo "<td><FORM ACTION=\"$PHP_SELF?Formation=433\" METHOD=\"POST\">";
	echo "<input name='code' type='submit' id='formation' value='4-3-3'>";
	echo "</form></td>";
	
	echo "<td><FORM ACTION=\"$PHP_SELF?Formation=343\" METHOD=\"POST\">";
	echo "<input name='code' type='submit' id='formation' value='3-4-3'>";
	echo "</form></td>";
	
	echo "<td><FORM ACTION=\"$PHP_SELF?Formation=532\" METHOD=\"POST\">";
	echo "<input name='code' type='submit' id='formation' value='5-3-2'>";
	echo "</form></td>";
	
	echo "<td><FORM ACTION=\"$PHP_SELF?Formation=randomteam\" METHOD=\"POST\">";
	echo "<input name='code' type='submit' id='formation' value='Pick Random Team'>";
	echo "</form></td>";
	
	
	
	echo "</td></tr></table>";
	
	echo "<tr><td>";
	if ($_SESSION['formation'] != 'randomteam')
	{
		echo "Set Formation: ".$_SESSION['formation'].". ";
	}
	echo "Current Formation:".$numGK."-".$numDEF."-".$numMID."-".$numATT.". ";
	if ($pass == 0)
		echo "Formation is INVALID";
	else
		echo "Formation is VALID";
	echo "</td></tr>";
	
	if ($_SESSION['formation'] == 'randomteam')
	{
		echo "<tr><td>Randomly Generated Team Name:";
		?>
		<SCRIPT>
		generateTeam();
		</SCRIPT>
		<?php
		echo "</td></tr>";
	}
		
	// Display this team
	echo "<tr>";
	$error = displayTeam($memberPlayer, $totalValue, MAXVALUE, $numGK, $numDEF, $numMID, $numATT);
	$error = displayPlayerList($_SESSION['position']);
	echo "</tr>";
	echo"</table>";
}

function randomTeam()
{
	// get random formation
	$formation = rand(0, 5);
	switch ($formation)
	{
		default:
		case 0 : $_SESSION['formation'] = 442; $def = 4; $mid = 4; $str = 2; break;
		case 1 : $_SESSION['formation'] = 433; $def = 4; $mid = 3; $str = 3; break;
		case 2 : $_SESSION['formation'] = 352; $def = 3; $mid = 5; $str = 2; break;
		case 3 : $_SESSION['formation'] = 343; $def = 3; $mid = 4; $str = 3; break;
		case 4 : $_SESSION['formation'] = 451; $def = 4; $mid = 5; $str = 1; break;
		case 5 : $_SESSION['formation'] = 532; $def = 5; $mid = 3; $str = 2; break;
	}

	// Get number of goalkeepers in list
	$cDatabase = new database();
	$connect = $cDatabase->connectToDatabase();
	$activeDatabase = $cDatabase->getActiveDatabase($connect);
	
	$db = $cDatabase->selectDatabase($connect, $activeDatabase);
	
	$selectArray[0] = '*';
	$result = $cDatabase->selectFromDatabase($connect, 'playerList', $selectArray, NULL, NULL, NULL, NULL);
	
	$numberRows = mysqli_num_rows($result);
	
	$tempPlayeCodeArray = array();
	for ($j = 0; $j < mysqli_num_rows($result); $j++)
	{
		$row = mysqli_fetch_array($result, MYSQLI_ASSOC);
		$tempPlayeCodeArray[$j] = $row['playerCode'];
	}
		
	$numberGoalkeepers = $cDatabase->GetNumberPlayersForPosition('GK', $connect);
	$numberDefenders = $cDatabase->GetNumberPlayersForPosition('DEF', $connect);
	$numberMidfielders = $cDatabase->GetNumberPlayersForPosition('MID', $connect);
	$numberStrikers = $cDatabase->GetNumberPlayersForPosition('STR', $connect);
	
	for ($n = 0; $n < 11; $n++)
	{
		if ($n == 0)
			$index = rand(0,($numberGoalkeepers-1));
		else if ($n <= $def) 
			$index = rand(($numberGoalkeepers), ($numberGoalkeepers+$numberDefenders-1));
		else if ($n <= ($def+$mid)) 
			$index = rand(($numberGoalkeepers+$numberDefenders), ($numberGoalkeepers+$numberDefenders+$numberMidfielders-1));
		else 
			$index = rand(($numberGoalkeepers+$numberDefenders+$numberMidfielders), ($numberRows-1));
			
		$_SESSION['playerArray'][$n] = $tempPlayeCodeArray[$index];
	}
	return $_SESSION['formation'];
}

function displayPlayerList($Position)
{
	$cDatabase = new database();

	$connect = $cDatabase->connectToDatabase();
	$activeDatabase = $cDatabase->getActiveDatabase($connect);
	
	$db = $cDatabase->selectDatabase($connect, $activeDatabase);

	$selectArray[0] = '*';
	//function selectFromDatabase($connect, $table, $selectArray, $whereString, $whereVar, $orderBy, $orderName)
	$result = $cDatabase->selectFromDatabase($connect, 'playerlist', $selectArray, 'playerPosition', $Position, NULL, NULL);

	if($result != 0)
	{
		echo"\n<td vAlign='top'>";
		echo "<table><tr><td>";
		
		echo "<td><FORM ACTION=\"$PHP_SELF?Posn=GK\" METHOD=\"POST\">";
		echo "<input name='code' type='submit' id='playerCode' value='GK'>";
		echo "</form></td>";
		
		echo "<td><FORM ACTION=\"$PHP_SELF?Posn=DEF\" METHOD=\"POST\">";
		echo "<input name='code' type='submit' id='playerCode' value='DEF'>";
		echo "</form></td>";
		
		echo "<td><FORM ACTION=\"$PHP_SELF?Posn=MID\" METHOD=\"POST\">";
		echo "<input name='code' type='submit' id='playerCode' value='MID'>";
		echo "</form></td>";
		
		echo "<td><FORM ACTION=\"$PHP_SELF?Posn=ATT\" METHOD=\"POST\">";
		echo "<input name='code' type='submit' id='playerCode' value='ATT'>";
		echo "</form></td>";
		echo "</td></tr></table>";
		
		echo "<table>";

		for ($i = 0; $i < mysqli_num_rows($result); $i++)
		{
			$row = mysqli_fetch_array($result, MYSQLI_ASSOC);
		
			echo "<tr><td>".$row['playerCode']."</td>";
			
			echo "<td><A STYLE='text-decoration:none;color:blue' href='DB_UserTeamBuilder.php?PlayerCodeIn=".$row['playerCode']."'>".$row['playerName']."</a></td>";
			
			echo "<td>".$row['playerTeam']."</td>";
			echo "<td>".$row['playerValue']."m</td>";
			//echo "<td>".$row['playerPosition']."</td>";
			echo "<td>".$row['playerLastYearScore']."</td></tr>";
		}
		echo "</table>";
		echo "</td>";
	}  //end else
}

function displayTeam($memberPlayer, $totalValue, $maxValue, $numGK, $numDEF, $numMID, $numATT)
{
	$PHP_SELF = $_SERVER['PHP_SELF'];

	echo"\n<td vAlign='top'>";
	echo "";
	echo "\n<FORM ACTION=\"$PHP_SELF?form=yes\" METHOD=\"POST\">";
	echo "\n<table width='600' border='0'>";
	for ($i = 1; $i <= 11; $i++)
	{
		if ($i < 10)
			$index = "0".$i;
		else
			$index = $i;
		
		$path = shirtLookup($memberPlayer[$i]->getTeam());
			
		echo"\n<tr>\n<td><img src='".$path."' width='50' height='50'></td><td>Player".$index."</td>";
		echo "<td><A STYLE='text-decoration:none;color:blue' href='DB_UserTeamBuilder.php?PlayerCodeOut=".$memberPlayer[$i]->getCode()."'><img src='images/Cancel.bmp'></a></td>";
		echo"\n<td>".$memberPlayer[$i]->getName()."</td>";
		//echo"\n<td><input type='text' name='playerCode".$index."' size='4' maxlength='4' value='".$memberPlayer[$i]->getCode()."'></td>";
		echo"\n<td>".$memberPlayer[$i]->getCode()."</td>";
		echo"\n<td>".$memberPlayer[$i]->getPosition()."</td>";
		echo"\n<td>".$memberPlayer[$i]->getTeam()."</td>";
		echo"\n<td>".$memberPlayer[$i]->getValue()."m</td>\n</tr>";
	}
	echo"\n<tr>";
	echo"\n<td></td>\n<td></td>\n<td></td>\n<td></td>";
	echo"\n<td>TOTAL</td><td>".$totalValue."m</td><td>Remaining</td>\n<td>".bcsub(MAXVALUE, $totalValue, 1)."m</td>";
	echo"\n</tr>";
	echo"\n</table>";
	echo"\n<BR>";
	
	echo"\n\n<table>";
	//echo "\n<td><input name='teamNameButton' type='submit' id='teamName' value='UPDATE'></td>";
	echo "\n</table>\n\n</form>";
	echo"\n</td>";
}

function shirtLookup($team)
{
	switch($team)
	{
		case "ARS"	: 	$path = "/JPEGs/Arsenal.gif";
						break;
		case "AVL"	: 	$path = "/JPEGs/AstonVilla.gif";
						break;
		case "BIR"	: 	$path = "/JPEGs/Birmingham.gif";
						break;
		case "BLA"	:	$path = "/JPEGs/Blackpool.gif";
						break;
		case "BLR"	: 	$path = "/JPEGs/Blackburn.gif";
						break;
		case "BOL"	: 	$path = "/JPEGs/Bolton.gif";
						break;
		case "BUR"	: 	$path = "/JPEGs/Burnley.gif";
						break;
		case "CHA"	: 	$path = "/JPEGs/Charlton.gif";
						break;
		case "DER"	: 	$path = "/JPEGs/Derby.gif";
						break;
		case "CHE"	: 	$path = "/JPEGs/Chelsea.gif";
						break;
		case "EVE"	: 	$path = "/JPEGs/Everton.gif";
						break;
		case "FUL"	: 	$path = "/JPEGs/Fulham.gif";
						break;
		case "HUL"	: 	$path = "/JPEGs/Hull.gif";
						break;
		case "LIV"	: 	$path = "/JPEGs/Liverpool.gif";
						break;
		case "MCY"	:
		case "MAN"	: 	$path = "/JPEGs/ManCity.gif";
						break;
		case "MUN"	: 	$path = "/JPEGs/manUtd.gif";
						break;
		case "MID"	: 	$path = "/JPEGs/Middlesbro.gif";
						break;
		case "NEW"	: 	$path = "/JPEGs/Newcastle.gif";
						break;
		case "NOR"	: 	$path = "/JPEGs/Norwich.gif";
						break;
		case "POR"	: 	$path = "/JPEGs/Portsmouth.gif";
						break;
		case "QPR"	: 	$path = "/JPEGs/QPR.gif";
						break;
		case "REA"	: 	$path = "/JPEGs/Reading.gif";
						break;
		case "SHF"	: 	$path = "/JPEGs/SheffUtd.gif";
						break;
		case "STO"	: 	$path = "/JPEGs/Stoke.gif";
						break;
		case "SUN"	: 	$path = "/JPEGs/Sunderland.gif";
						break;
		case "SWA"	: 	$path = "/JPEGs/Swansea.gif";
						break;
		case "TOT"	: 	$path = "/JPEGs/Tottenham.gif";
						break;
		case "WAT"	: 	$path = "/JPEGs/Watford.gif";
						break;
		case "WBA"	: 	$path = "/JPEGs/WestBrom.gif";
						break;
		case "WHM"	: 	$path = "/JPEGs/WestHam.gif";
						break;
		case "WIG"	: 	$path = "/JPEGs/Wigan.gif";
						break;
		case "WLV"	:
		case "WOL"	: 	$path = "/JPEGs/Wolves.gif";
						break;
		default		: 	$path = "/JPEGs/Blank.gif";
						break;
	}
	return $path;
}

echo $cPage->getContentStringEnd();
echo $cPage->getMenu();
echo $cPage->getClear();
echo $cPage->pageStringEnd();
?>